package com.lms.service.update;

import com.alibaba.excel.EasyExcel;
import com.lms.bean.User;
import com.lms.listener.ExcelDataListener;
import com.lms.util.Constants;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class UploadServiceImpl implements UploadService{
    /*设置临时文件存放地址*/
    public static String TEMP_FOLDER="/temp_folder";

    @Override
    public String saveFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        /*配置参数*/
        List<FileItem> fileItems=null;//存放上传文件的集合
        String fileName=null;

        /*防乱码*/
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        /*设置磁盘管理*/
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();//in comment-io.jar
        diskFileItemFactory.setRepository(new File(TEMP_FOLDER));// 设置磁盘存储区域
        diskFileItemFactory.setSizeThreshold(1024*1024);//设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室

        /*解析请求上传的文件*/
        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);//in comment-fileupload
        try {
            fileItems = upload.parseRequest(request);
            /*保存上传文件*/
            for (FileItem file:fileItems){
                fileName=file.getName();
                InputStream in = file.getInputStream();
                File path = new File(Constants.EXCEL_FOLDER);
                if (!path.isDirectory()){/*当定义存储excel的文件夹，没有被创建，需要事先建好*/
                    path.mkdir();
                }
                FileOutputStream out = new FileOutputStream(Constants.EXCEL_FOLDER + fileName);
                byte[] buff=new byte[1024];
                int len=0;
                while ((len=in.read(buff))>0){
                    out.write(buff);
                }
                in.close();
                out.close();
            }
        } catch (Exception e) {
            return null;
        }
        return fileName;
    }

    @Override
    public void excel(String fileName) {
        EasyExcel.read(Constants.EXCEL_FOLDER+fileName, User.class,new ExcelDataListener(0)).sheet("学生").doRead();
        EasyExcel.read(Constants.EXCEL_FOLDER+fileName, User.class,new ExcelDataListener(1)).sheet("教师").doRead();
    }
}